// 日志记录工具类
export enum LogLevel {
  DEBUG = 0,
  INFO = 1,
  WARN = 2,
  ERROR = 3
}

export class Logger {
  private static instance: Logger
  private logLevel: LogLevel = LogLevel.DEBUG
  private logToFile: boolean = false

  private constructor() {}

  static getInstance(): Logger {
    if (!Logger.instance) {
      Logger.instance = new Logger()
    }
    return Logger.instance
  }

  setLogLevel(level: LogLevel): void {
    this.logLevel = level
  }

  enableFileLogging(enable: boolean): void {
    this.logToFile = enable
  }

  debug(message: string, ...args: any[]): void {
    if (this.logLevel <= LogLevel.DEBUG) {
      this.log('DEBUG', message, ...args)
    }
  }

  info(message: string, ...args: any[]): void {
    if (this.logLevel <= LogLevel.INFO) {
      this.log('INFO', message, ...args)
    }
  }

  warn(message: string, ...args: any[]): void {
    if (this.logLevel <= LogLevel.WARN) {
      this.log('WARN', message, ...args)
    }
  }

  error(message: string, ...args: any[]): void {
    if (this.logLevel <= LogLevel.ERROR) {
      this.log('ERROR', message, ...args)
    }
  }

  private log(level: string, message: string, ...args: any[]): void {
    const timestamp = new Date().toISOString()
    const logMessage = `[${timestamp}] [${level}] ${message}`
    
    // 控制台输出
    switch (level) {
      case 'DEBUG':
        console.debug(logMessage, ...args)
        break
      case 'INFO':
        console.info(logMessage, ...args)
        break
      case 'WARN':
        console.warn(logMessage, ...args)
        break
      case 'ERROR':
        console.error(logMessage, ...args)
        break
      default:
        console.log(logMessage, ...args)
    }
    
    // 如果启用文件日志记录，发送到主进程
    if (this.logToFile) {
      try {
        (window as any).electronAPI?.logMessage?.(level, message, ...args)
      } catch (error) {
        // 忽略日志记录错误，避免影响主流程
      }
    }
  }
}

// 创建默认实例
export const logger = Logger.getInstance()